package com.geekcoding.geekoj.repository;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geekcoding.geekoj.entity.BaseEntity;
import com.google.common.collect.Lists;

import java.util.List;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * @author xiaobai
 * @since 2024/02/25 14:17
 **/
public abstract class BaseRepository<E extends BaseEntity, T, M extends BaseMapper<E>> extends ServiceImpl<M, E> {

    public abstract T convert(E entity);

    public List<T> convertList(List<E> eList) {
        if (Objects.isNull(eList)) {
            return Lists.newArrayList();
        }
        return eList.stream().map(this::convert).collect(Collectors.toList());
    }

    public T queryById(String id) {
        if (StrUtil.isBlank(id)) {
            return null;
        }
        return convert(baseMapper.selectById(id));
    }

    public Page<E> queryByPage(Page<E> page, Consumer<Wrapper<E>> consumer) {
        Wrapper<E> queryWrapper = new LambdaQueryWrapper<>();
        if (Objects.nonNull(consumer)) {
            consumer.accept(queryWrapper);
        }
        return this.page(page, queryWrapper);
    }
}
